<?php
namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;
use app\service\TopviewApiService;
use app\service\OssService;

class SyncProductAnyShootTemplates extends Command
{
    protected function configure()
    {
        $this->setName('sync:product-anyshoot-templates')
            ->setDescription('每日同步 Product AnyShoot 模板列表，下载图片并上传OSS，入库供查询');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('开始同步 Product AnyShoot 模板...');
        $api = new TopviewApiService();
        $oss = new OssService();

        $pageNo = 1;
        $pageSize = 100;
        $totalSynced = 0;

        try {
            do {
                $output->writeln("正在处理第 {$pageNo} 页...");
                $result = $api->getProductAnyShootTemplateList('', '', $pageNo, $pageSize);

                $list = $result['data'] ?? ($result['list'] ?? []);
                $total = $result['total'] ?? count($list);
                if (empty($list)) {
                    $output->writeln("第 {$pageNo} 页数据为空，结束同步");
                    break;
                }

                $output->writeln("第 {$pageNo} 页获取到 " . count($list) . " 条数据，开始处理...");
                
                // 调试：显示第一条数据的结构
                if ($pageNo == 1 && !empty($list)) {
                    $output->writeln("调试 - 第一条数据结构:");
                    $output->writeln("  " . json_encode($list[0], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
                }
                
                $pageSuccessCount = 0;
                $pageFailCount = 0;

                foreach ($list as $index => $item) {
                    $itemIndex = $index + 1;
                    $templateId = $item['templateId'] ?? '';
                    $output->writeln("  处理第 {$itemIndex} 条: templateId={$templateId}");
                    try {
                        if (empty($templateId)) {
                            $output->writeln("    -> 跳过：templateId 为空");
                            $pageFailCount++;
                            continue;
                        }

                        $templateImageUrl = $item['templateImageUrl'] ?? '';
                        $ossUrl = null;
                        if ($templateImageUrl) {
                            $output->writeln("    -> 下载图片: {$templateImageUrl}");
                            
                            // 使用 cURL 下载，添加更多调试信息
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $templateImageUrl);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; ProductAnyShoot/1.0)');
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                            
                            $content = curl_exec($ch);
                            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            $error = curl_error($ch);
                            curl_close($ch);
                            
                            if ($content !== false && $httpCode == 200) {
                                $tmp = tempnam(sys_get_temp_dir(), 'tpl_');
                                file_put_contents($tmp, $content);
                                try {
                                    $object = 'product_anyshoot/templates/' . date('Ymd') . '/' . $templateId . '.jpg';
                                    $output->writeln("    -> 上传OSS: {$object}");
                                    $ossUrl = $oss->putObject($object, $tmp);
                                    $output->writeln("    -> OSS地址: {$ossUrl}");
                                } finally {
                                    @unlink($tmp);
                                }
                            } else {
                                $output->writeln("    -> 警告：图片下载失败 - HTTP状态码: {$httpCode}");
                                if ($error) {
                                    $output->writeln("    -> cURL错误: {$error}");
                                }
                                if ($httpCode != 200) {
                                    $output->writeln("    -> 非200状态码，可能URL无效或需要认证");
                                }
                            }
                        } else {
                            $output->writeln("    -> 跳过：无图片URL");
                        }

                        // 处理分类信息
                        $categoryId = null;
                        $categoryName = null;
                        if (isset($item['templateCategoryList']) && is_array($item['templateCategoryList']) && !empty($item['templateCategoryList'])) {
                            $categoryId = $item['templateCategoryList'][0]['categoryId'] ?? null;
                            $categoryName = $item['templateCategoryList'][0]['categoryName'] ?? null;
                        }

                        // upsert
                        $now = date('Y-m-d H:i:s');
                        $data = [
                            'template_id' => $templateId,
                            'category_id' => $categoryId,
                            'category_name' => $categoryName,
                            'template_name' => $item['templateName'] ?? null,
                            'template_description' => $item['templateDescription'] ?? null,
                            'template_image_url' => $templateImageUrl,
                            'oss_image_url' => $ossUrl,
                            'style' => $item['style'] ?? null,
                            'tags' => isset($item['tags']) ? json_encode($item['tags'], JSON_UNESCAPED_UNICODE) : null,
                            'prompt' => $item['prompt'] ?? null,
                            'source' => 'v1',
                            'update_time' => $now,
                        ];

                        $exists = Db::name('product_anyshoot_templates')->where('template_id', $templateId)->find();
                        if ($exists) {
                            $output->writeln("    -> 更新数据库记录 (ID: {$exists['id']})");
                            Db::name('product_anyshoot_templates')
                                ->where('id', $exists['id'])
                                ->update($data);
                        } else {
                            $output->writeln("    -> 插入新数据库记录");
                            $data['create_time'] = $now;
                            Db::name('product_anyshoot_templates')->insert($data);
                        }

                        $totalSynced++;
                        $pageSuccessCount++;
                        $output->writeln("    -> 成功处理");
                    } catch (\Exception $e) {
                        Log::error('同步单条 Product AnyShoot 模板失败', [
                            'error' => $e->getMessage(), 
                            'item' => $item
                        ]);
                        $output->writeln('    -> 失败: ' . $e->getMessage());
                        $pageFailCount++;
                    }
                }

                $output->writeln("第 {$pageNo} 页处理完成 - 成功: {$pageSuccessCount}, 失败: {$pageFailCount}");
                $output->writeln("休息 0.2 秒后继续下一页...");

                $pageNo++;
                // 小憩避免打爆接口
                usleep(200000);
            } while (($pageNo - 1) * $pageSize < ($total ?? PHP_INT_MAX));

            $output->writeln('==========================================');
            $output->writeln('同步完成！');
            $output->writeln("总计处理: {$totalSynced} 条记录");
            $output->writeln('==========================================');
        } catch (\Exception $e) {
            Log::error('同步 Product AnyShoot 模板失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            $output->writeln('执行失败: ' . $e->getMessage());
        }
    }
}
